<script setup lang="ts">

import { ref, computed, watch, getCurrentInstance, onMounted } from "vue";
import { callApiEventEmitter } from "@/utils/eventBus";

import App from "@iconify-icons/ri/apps-line";
import OfficeBuilding from "@iconify-icons/ep/office-building";
import LocationCompany from "@iconify-icons/ep/add-location";
interface Tree {
  pid: number;
  nodeName: string;
  highlight?: boolean;
  children?: Tree[];
}

defineProps({
  treeLoading: Boolean,
  treeData: Array
});

const emit = defineEmits(["tree-select-call"]);

const treeRef = ref();
const isExpand = ref(true);
const searchValue = ref("");
const highlightMap = ref({});
const { proxy } = getCurrentInstance();
const defaultProps = {
  children: "children",
  label: "nodeName"
};

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.nodeName.includes(value);
};

function nodeClick(value) {

  const nodeId = value.$treeNodeId ?? "root";
  highlightMap.value[nodeId] = highlightMap.value[nodeId]?.highlight
    ? Object.assign({ pid: nodeId }, highlightMap.value[nodeId], {
      highlight: false
    })
    : Object.assign({ pid: nodeId }, highlightMap.value[nodeId], {
      highlight: true
    });
  Object.values(highlightMap.value).forEach((v: Tree) => {
    if (v.pid !== nodeId) {
      v.highlight = false;
    }
  });
  emit(
    "tree-select-call",
    highlightMap.value[nodeId]?.highlight
      ? Object.assign({ ...value, selected: true })
      : Object.assign({ ...value, selected: false })
  );

}

function toggleRowExpansionAll(status) {
  isExpand.value = status;
  const nodes = (proxy.$refs["treeRef"] as any).store._getAllNodes();
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].expanded = status;
  }
}

/** 重置应用清单状态（选中状态、搜索框值、树初始化） */
function onTreeReset() {
  highlightMap.value = {};
  searchValue.value = "";
  toggleRowExpansionAll(true);
}

watch(searchValue, val => {
  treeRef.value!.filter(val);
});

defineExpose({ onTreeReset });
callApiEventEmitter.on("clickServiceCard", nodeClick);
</script>

<template>
  <div v-loading="treeLoading" class="h-full bg-bg_color overflow-auto" :style="{ minHeight: `calc(100vh - 141px)` }">
    <div class="flex items-center h-[34px]">
      <el-input v-model="searchValue" class="ml-2" size="small" placeholder="请输入应用名称" clearable>
        <template #suffix>
          <el-icon class="el-input__icon">
            <IconifyIconOffline v-show="searchValue.length === 0" icon="ri:search-line" />
          </el-icon>
        </template>
      </el-input>

    </div>
    <el-divider />
    <el-tree ref="treeRef" :data="treeData" node-key="id" size="small" :props="defaultProps" default-expand-all
      :expand-on-click-node="false" :filter-node-method="filterNode" @node-click="nodeClick">
      <template #default="{ node, data }">
        <span :class="[
          'pl-1',
          'pr-1',
          'rounded',
          'flex',
          'items-center',
          'select-none',
          'hover:text-primary',
          searchValue.trim().length > 0 &&
          node.label.includes(searchValue) &&
          'text-red-500',
          highlightMap[node.id]?.highlight ? 'dark:text-primary' : ''
        ]" :style="{
          color: highlightMap[node.id]?.highlight
            ? 'var(--el-color-primary)'
            : '',
          background: highlightMap[node.id]?.highlight
            ? 'var(--el-color-primary-light-7)'
            : 'transparent'
        }">
          <IconifyIconOffline :icon="data.type === 1
            ? OfficeBuilding
            : data.type === 2
              ? LocationCompany
              : App
            " />
          {{ node.label }}
        </span>
      </template>
    </el-tree>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-divider) {
  margin: 0;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: transparent;
}
</style>
